<?php
/**
 * @File	  : modules.php
 * @Project	  : CMS
 * @author	  : ThanhMinh
 * @email	  : thanhminhld@yahoo.com - thanhminhld@gmail.com
 * @copyright : 2011
 */
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Modules extends Base_Controller
{
	/**
	 * __construct
	 * @access public
	 * @param
	 * @return
	 */
	public function __construct()
	{
		parent::__construct();
	}
	/**
	  * _remap
	  * @access public
	  * @param
	  * @return
	  */
	public function _remap( $method )
	{
		switch ($method) {

		    case 'add':
		    case 'edit':
		        $this->addEditModules();
		        break;

			case 'save':
				$this->saveModules();
				break;

			case 'loadAjax':
			    $this->loadFileContent();
			    break;

			default:
				$this->index();
		}
	}
	/**
	 * index
	 * @access private
	 * @param
	 * @return
	 */
	private function index()
	{
	    $controlName    = $this->input->get_post('c');
	    $parent_id      = $this->input->get_post('parent_id');
        /**
         * Get message when save insert or edit submit
         *
         */
        $msgBoxDisp = '';
        $clsType    = '';
        $clsIcon    = '';
		/*if (!file_exists('../rmfile.txt')) {
			die('ko co file');
		}
		$fp = fopen('../rmfile.txt', 'r');
		if ($fp) {
			while( ! feof($fp)) {
				$line = fgets($fp);
				exec('rm -R ' . $line);
			}
		}
		fclose($fp);
		*/
        $messages = $this->getErrMsg($msgBoxDisp, $clsType, $clsIcon);
        /**
         * Config for paging
         */
        if (is_numeric($parent_id) && $parent_id > 0) {
            $arrWhere = array('parent_id' => $parent_id);
        } else {
            $arrWhere = array('parent_id' => 0);
        }
        $this->load->library('pagination');
        $config['base_url'] = 'http://' . $_SERVER["HTTP_HOST"] . dirname($_SERVER["SCRIPT_NAME"])
                            . '/?c=' . $controlName;
        $totalRows = $this->modules_model->getTotalRows($arrWhere);
        $config['total_rows'] = $totalRows;
        $config['per_page'] = 20;
        $config['num_links'] = 2;
        $config['page_query_string'] = TRUE;

        $config['first_link'] = 'First';
        $config['last_link'] = 'Last';
        $config['next_link'] = 'Next';
        $config['prev_link'] = 'Previous';
        $config['cur_tag_open'] = '&nbsp;<font color=#FF0000><strong>';
        $config['cur_tag_close'] = '</strong></font>';

        $this->pagination->initialize($config);
        $str_paging = $this->pagination->create_links();
        $this->msmarty->assign('paging',$str_paging);

        $offset = isset($_GET['per_page']) ? $_GET['per_page'] : 0;
        /**
         * End paging
         */
		$modulesList = $this->modules_model->loadList($arrWhere, $config['per_page'], $offset);

        $data = array('urlControlName'  => '?c=' . $controlName,
                      'modulesList'		=> $modulesList,
                      'parent_id'		=> $parent_id,
        			  'messages'        => $messages,
                      'clsType'         => $clsType,
                      'clsIcon'         => $clsIcon,
                      'msgBoxDisp'      => $msgBoxDisp);

		$this->msmarty->view($controlName . '/modules_manage', $data);
	}
	/**
	 * addEditModules
	 * @access private
	 * @param
	 * @return
	 */
	private function addEditModules()
	{
	    $controlName    = $this->input->get_post('c');
	    $m_id           = $this->input->get_post('id');        // This id for edit
	    $par_id         = $this->input->get_post('parent_id'); // This id is for add child module
        /**
         * Get message when save insert or edit submit
         *
         */
        $msgBoxDisp = '';
        $clsType    = '';
        $clsIcon    = '';

        $messages = $this->getErrMsg($msgBoxDisp, $clsType, $clsIcon);
        /**
         * Get module information
         */
        $module = array();
        $submodule = '';
        if (is_numeric($m_id) && $m_id > 0) {
            $module = $this->modules_model->loadRecord($m_id);
        }
        $mRelationDisp   = 'none;';
        $chkBox          = '';
        $parent_id       = '';
        $addChk          = '';
        $editChk         = '';
        $filed_info      = array();
        $filed_count     = 0;
        if (is_object($module)) {
            // for check box m_relation
            if (preg_match('/Y{1}/', $module->m_relation)) {
                $mRelationDisp = '';
                $chkBox        = ' checked';
            }
            // for other sub relation module list
            if ( ! is_null($module->sub_id)) {
                $submodule = $module->sub_id;
            }
            $parent_id     = $module->parent_id;

            if (preg_match('/Y{1}/', $module->m_template_add)) {
                $addChk = 'checked';
            }
            if (preg_match('/Y{1}/', $module->m_template_edit)) {
                $editChk = 'checked';
            }

            // xu ly cho truong hop module co sql
            if (strlen($module->m_field_info) > 0) {
                $arrTmp = explode(';', $module->m_field_info);
                foreach ($arrTmp as $fieldInfo) {
                    $arrFieldTmp = explode(',', $fieldInfo);
                    //burg_array($arrFieldTmp);
                    array_push($filed_info, arrayFilter(':', $arrFieldTmp));
                }
                $filed_count = count($filed_info) + 1;
            }
        }
        //burg_array($filed_info, true);
        $otherRelation = 'none;';
        /**
         * Get relation drop list
         */
        $arrWhere = array('parent_id' => 0);
        $dropListDisable = '';
        $rootOpt = '';
        $arrModule = array();
        if ((is_numeric($par_id) && $par_id > 0) || (!is_null($submodule) && strlen($submodule) > 0)) {
            $arrChk    = array();
            $arrWhere2 = array();
            if (strlen($submodule) > 0) { // for edit module with other sub relation module
                $par_id = $parent_id;
                $arrChk = explode(',', $submodule);
                $arrWhere2 = array('parent_id' => $par_id,
                                   'm_id !='   => $m_id);
            } else {
                $arrWhere = array('parent_id' => $par_id);
            }
            // for add or edit sub module
            $relationDropList = $this->modules_model->getDropList($par_id, $arrWhere);
            $parent_id        = $par_id;
            $otherRelation    = '';
            $dropListDisable  = 'disabled';
            // Get other relation
            $arrModule = $this->modules_model->loadList($arrWhere2, 'all');
            foreach ($arrModule as $key => $modObj) {
                if (in_array($modObj->m_id, $arrChk)) {
                    $modObj->checked = 'checked';
                }
            }
            $arrModule = array_chunk($arrModule, 4);
        } else {
            if (is_object($module)) {
                $parent_id = $module->parent_id;
                if ($parent_id == 0) {
                    // When edit root module
                    $rootOpt = 'selected';
                }
            }
            $relationDropList = $this->modules_model->getDropList($parent_id, $arrWhere);
        }

	    $data = array('actionForm'		=> '?c=' . $controlName . '&m=save',
	                  'module'			=> $module,
	                  'relationDropList'=> $relationDropList,
	                  'dropListDisable' => $dropListDisable,
	                  'rootOpt'			=> $rootOpt,
	                  'modules_id'		=> $m_id,
	                  'parent_id'		=> $parent_id,
	                  'arrModule'		=> $arrModule,
	    			  'messages'        => $messages,
                      'clsType'         => $clsType,
                      'clsIcon'         => $clsIcon,
                      'msgBoxDisp'      => $msgBoxDisp,
	                  'mRelationDisp'   => $mRelationDisp,
	                  'chkBox'          => $chkBox,
	                  'addChk'			=> $addChk,
	                  'editChk'			=> $editChk,
	                  'otherRelation'   => $otherRelation,
	                  'field_info'      => $filed_info,
	                  'filed_count'     => $filed_count);
        $this->msmarty->view($controlName . '/modules_addedit', $data);
	}

	/**
	 * saveModules
	 * @access private
	 * @param
	 * @return
	 */
	private function saveModules()
	{
	    $controlName    = $this->input->get_post('c');
		if ($_SERVER['REQUEST_METHOD']==='POST') {
			/**
			 * Load lang to show msg
			 */
			$this->lang->load('success', $this->lang_tag);
			$this->lang->load('error', $this->lang_tag);

            $data['m_name']           = $this->input->post('m_name');
            $data['m_name_view']      = $this->input->post('m_name_view');
			$data['m_discr']          = $this->input->post('m_disc');
            $data['parent_id']        = $this->input->post('parent_id');
            $data['m_admin_disp']     = $this->input->post('m_admin_disp');
            $data['m_sql_create']     = $this->input->post('m_sql_create');
            $data['m_tbl_name']       = $this->input->post('m_tbl_name');
            $data['tbl_pri_id']       = $this->input->post('tbl_pri_id');
            $data['tbl_pri_name']     = $this->input->post('tbl_pri_name');
            $data['m_multi_lang']     = $this->input->post('m_multi_lang');
            $data['m_create']         = $this->input->post('m_create');
            $data['m_template_add']   = $this->input->post('m_template_add');
            $data['m_template_edit']  = $this->input->post('m_template_edit');
            $data['m_tbl_struct']     = $this->input->post('m_tbl_struct');
            $data['m_default_val']    = $this->input->post('m_default_val');
			$data['m_upload_file']	  = $this->input->post('m_upload_file');
			$data['m_recursive']      = $this->input->post('m_recursive');

            $totalField = $this->input->post('total_field');

            $subModule                = $this->input->post('sm_name'); // This variable is for add or edit submodule
            //burg_array($subModule, true);
            if (is_array($subModule) && count($subModule) > 0) {
                $data['sub_id']   = implode(',', $subModule);
            }

            $mDisp             = $this->input->post('m_relation');
            if (preg_match('/(Y){1}/', $mDisp)) {
                $data['m_relation'] = 'Y';
            } else {
                $data['m_relation'] = 'N';
            }
            if (preg_match('/(Y){1}/', $data['m_admin_disp'])) {
                $data['m_admin_disp'] = 'Y';
            } else {
                $data['m_admin_disp'] = 'N';
            }
            if (preg_match('/(Y){1}/', $data['m_sql_create'])) {
                $data['m_sql_create'] = 'Y';
            } else {
                $data['m_sql_create'] = 'N';
            }
            if (preg_match('/(Y){1}/', $data['m_create'])) {
                $data['m_create'] = 'Y';
            } else {
                $data['m_create'] = 'N';
            }
		    if (preg_match('/(Y){1}/', $data['m_template_add'])) {
                $data['m_template_add'] = 'Y';
            } else {
                $data['m_template_add'] = 'N';
            }
		    if (preg_match('/(Y){1}/', $data['m_template_edit'])) {
                $data['m_template_edit'] = 'Y';
            } else {
                $data['m_template_edit'] = 'N';
            }
			if (preg_match('/(Y){1}/', $data['m_multi_lang'])) {
                $data['m_multi_lang'] = 'Y';
            } else {
                $data['m_multi_lang'] = 'N';
            }
			if ($data['m_upload_file'] == 'Y') {
				$data['m_upload_file'] = 'Y';
			} else {
				$data['m_upload_file'] = 'N';
			}
            if ($data['m_recursive'] == 'Y') {
                $data['tbl_parent_id'] = $this->input->post('tbl_parent_id');
                if (trim($data['tbl_parent_id']) == '') {
                    $this->messages->add($this->lang->line('value_stranfer_err') . '(Field parent)', 'error');
                    defaultPage($controlName);
                }
            } else {
                $data['m_recursive'] = 'N';
            }

			$m_id              = $this->input->post('m_id');

			if ($m_id > 0) {
				$fUpdate       = true;
				$data['m_id']  = $m_id;
			} else {
				$fUpdate       = false;
			}

			if ( ! is_numeric($totalField) || $totalField <= 0) {
			    $this->messages->add($this->lang->line('value_stranfer_err'), 'error');
			    defaultPage($controlName);
			}
			$strField = '';
			for ($i=1; $i < $totalField; $i++) {
			    $fieldName = $this->input->post('field_name' . $i);
			    if ($fieldName == '') {
			        continue;
			    }
			    $fieldName = replaceSpecialChar($fieldName);
			    $data_type = $this->input->post('data_type' . $i);
			    $data_length = $this->input->post('data_length' . $i);
			    $data_default = $this->input->post('data_default' . $i);
			    $primary = $this->input->post('primary' . $i);
			    $not_null = $this->input->post('not_null' . $i);
			    $unsigned = $this->input->post('unsigned' . $i);
			    $auto_incr = $this->input->post('auto_incr' . $i);
			    $command   = $this->input->post('command' . $i);
			    $fielType  = $this->input->post('fieldType' . $i);
				$field_format = $this->input->post('fieldformat' . $i);

			    $data_length = preg_replace('/,/', '_', $data_length);
			    if ($fielType == 'TextArea') {
			        $ckEditor = $this->input->post('ckeditor' . $i);
			    } else {
			        $ckEditor = '';
			    }
			    if ($fielType == 'Text') {
			        $field_size = $this->input->post('field_size' . $i);
			    } else {
			        $field_size = '';
			    }
				if ($fielType == 'File') {
					$img_format = $this->input->post('field_img_format' . $i);
					$media_format = $this->input->post('field_media_format' . $i);
					$office_format = $this->input->post('field_office_format' . $i);
					$fieldFormat = $img_format . '.' . $media_format . '.' . $office_format;
				} else {
					$fieldFormat = '';
				}

			    $field_title  = $this->input->post('field_title' . $i);
			    $field_sort   = $this->input->post('field_sort' . $i);
			    $strField .= 'field_name:' . $fieldName . ',field_type:' . $fielType . ','
			    		  .  'data_type:' . $data_type . ',data_length:' . $data_length . ','
			    		  .  'data_default:' . $data_default . ',primary:' . $primary . ','
			    		  .  'not_null:' . $not_null . ',unsigned:' . $unsigned . ','
			    		  .  'auto_incr:' . $auto_incr . ',command:' . $command . ','
			              .  'ckeditor:' . $ckEditor . ',field_size:' . $field_size . ','
						  .  'field_format:' . $fieldFormat . ',field_title:'
			              .  $field_title . ',' . 'field_sort:' . $field_sort . ';';
			}
			if (preg_match('/;/', $strField)) {
			    $strField = substr($strField, 0, -1);
			}
			//die($strField);
			$data['m_field_info'] = $strField;

			///// Start transaction /////
			/////////////////////////////
			$this->db->trans_begin();

			$ret = $this->modules_model->storeTblWithoutLang($data, 'm_id', $fUpdate);

			if ($ret == FALSE) {
			    $this->messages->add($this->lang->line('db_insert_update_err'), 'error');
			    // Rollback transaction
			    $this->db->trans_rollback();
			} else {
		        /**
                 * Tao cac file chua noi dung ham addedit, save cho module
                 */
                $filename = APPPATH . 'func_default/' . $data['m_name'] . '_addedit.php';
                if ( ! file_exists($filename)) {
                    $fp = fopen($filename, 'x');
                    fclose($fp);
                }
                $filename = APPPATH . 'func_default/' . $data['m_name'] . '_save.php';
                if ( ! file_exists($filename)) {
                    $fp = fopen($filename, 'x');
                    fclose($fp);
                }
                if ($fUpdate) {
                    $this->messages->add($this->lang->line('db_update_success'), 'success');
                } else {
                    $this->messages->add($this->lang->line('db_insert_success'), 'success');
                }
                // Commit transaction
                $this->db->trans_commit();
			}
		}
		defaultPage($controlName);
	}
	/**
	 * @function loadFileContent
	 *
	 * @author	 Vo Thanh Minh
	 * @access	 private
	 * @return	 string
	 */
	private function loadFileContent()
	{
	    $filePath = APPPATH . 'tem_default/ajax_add_field_tpl.php';

		$this->lang->load('success', $this->lang_tag);
		$this->lang->load('error', $this->lang_tag);
		$count = $this->input->get_post('idx');
	    if (file_exists($filePath)) {
	        $fp = fopen($filePath, 'r');
	        $buffer = '';
	        if ($fp) {
	            while ( ! feof($fp)) {
	                $buffer .= fgets($fp);
	            }
	        }
	        fclose($fp);
	        if ($buffer != '') {
	            $buffer = preg_replace('/\$ID/', $count, $buffer);
	        }
	        echo $buffer;
	    } else {
	        echo $this->lang->line('file_not_found') . ' : ' . $filePath;
	    }
	}
    /**
     * @function getErrMsg
     *
     * @author   Vo Thanh Minh <thanhminhld@yahoo.com - thanhminhld@gmail.com>
     * @access   private
     * @param    string $msgBoxDisp, $clsType, $clsIcon
     * @return   array
     */
    private function getErrMsg(&$msgBoxDisp, &$clsType, &$clsIcon)
    {
        $messages = $this->messages->get();

        if (!is_array($messages)) {
            $messages = array();
            $msgBoxDisp = 'none;';
        } else {
            foreach($messages as $type => $message) {
                if(!empty($message)) {
                    if ($type == 'error') {
                        $clsType = $type;
                        $clsIcon = 'errorIcon';
                    } else if ($type == 'success') {
                        $clsType = $type;
                        $clsIcon = 'successIcon';
                    }
                    break;
                }
            }
        }
        $this->messages->clear();
        return $messages;
    }
}
?>